package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.mvp.presenter.LoginPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.LoginPersenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.LoginView;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.utils.UpdateManager;
import com.example.codeutils.utils.AppUtils;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.MapUtil;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import master_bean.AppUpdateBean;
import rxretrofit_base.model.FileLoadingBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

/**
 * Created by Jason Chen on 2017/2/20.
 * 登录
 */
public class LoginActivity extends BaseActivity implements LoginView {
    @InjectView(R.id.edit_username)
    EditText usernameEdit;
    @InjectView(R.id.edit_password)
    EditText passwordEdit;
    @InjectView(R.id.btn_login)
    Button loginBtn;
    @InjectView(R.id.appVersionNameTv)
    TextView appVersionTv;

    private LoginPresenter loginPersenter;
    private String username;
    private String password;
    private boolean isClick = false;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginPersenter = new LoginPersenterImpl(this);
        ButterKnife.inject(this);
        username = CustomSharedPreferences.getString(this, KeyBean.USER_NAME.valueOf(), KeyBean.FILE_NAME.valueOf());
        password = CustomSharedPreferences.getString(this, KeyBean.PASSWORD.valueOf(), KeyBean.FILE_NAME.valueOf());
        if (!TextUtils.isEmpty(username)) {
            usernameEdit.setText(username);
        }
        if (!TextUtils.isEmpty(password)) {
            passwordEdit.setText(password);
        }
        appVersionTv.setText("当前版本号："+AppUtils.getAppVersionName(this));
        int mVersion_code = AppUtils.getAppVersionCode(this);// 当前的版本号
        Logger.d(mVersion_code+"");
        getVisern(mVersion_code);
        if((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0){
            finish();
            return;
        }
    }
    private void getVisern(int version) {
        HashMap<String,Object> map = new MapUtil()
                .put("version",1)
                .put("url",true).build();
        RxRequest.request(ShowType.DISMISS, RxRequest.getClient(LoginActivity.this, map).create(IApiActivityRequest.class).appVersion(),
                new BaseSubscriber<TokenBean<AppUpdateBean>>(LoginActivity.this) {
                    @Override
                    public void onSuccess(TokenBean<AppUpdateBean> o) {
                        isClick = true;
                        if(o.getData()!=null){
                            Logger.d("  =="+o.getData().getUrl());
                            String url = o.getData().getUrl();
                            String version_info = "\t\t\t发现新的版本,是否更新？";
                            showProgressDialog();
                            new UpdateManager(LoginActivity.this).showNoticeDialog(version_info,url, mProgressDialog);
                        }else{
                            autoLogin();
                        }
                    }
                    @Override
                    public void onFailure(Throwable e) {
                        isClick = true;

                    }
                });
    }

    /**
     * 判断密码是否正确，正确就跳转
     */
    @Override
    public void login() {
        //判断账号密码是否正确，如果正确则跳转主界面，如果错误则提示
        HashMap<String, Object> build = new MapUtil()
                .put(KeyBean.USER_NAME.valueOf(), usernameEdit.getText().toString())
                .put(KeyBean.PASSWORD.valueOf(), passwordEdit.getText().toString())
                .build();
        CrashReport.setUserId(usernameEdit.getText().toString()); //设置 bugly 返回用户id
        CustomSharedPreferences.saveString(this, build, KeyBean.FILE_NAME.valueOf());   //保存密码
        startIntent(new Intent(LoginActivity.this, MainActivity.class), true);
    }
    /**
     * 自动登录
     */
    public void autoLogin(){
        if(!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)){
            loginPersenter.requestLogin(username, password);
        }
    }
    @OnClick(R.id.btn_login)
    public void onClick() {
        if(isClick){
            loginPersenter.requestLogin(usernameEdit.getText().toString(), passwordEdit.getText().toString());
        }else{
            showToast("检测更新，请稍后...");
        }
    }

    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if (rxBusBean.getO() instanceof FileLoadingBean) {
            FileLoadingBean fileLoadingBean = (FileLoadingBean)rxBusBean.getO();
            int progress =(int)(fileLoadingBean.getProgress() * 100 / fileLoadingBean.getTotal());
                mProgressDialog.setProgress(progress);
                if (progress == 99) {
                    mProgressDialog.dismiss();
                }
        }
    }

    private void showProgressDialog() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("正在下载");
        mProgressDialog.setMax(100);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMessage("请稍候...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCanceledOnTouchOutside(false);

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
